package com.xjx.service.Impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xjx.constant.RedisConstant;
import com.xjx.dao.SetMealDao;
import com.xjx.entity.PageResult;
import com.xjx.entity.QueryPageBean;
import com.xjx.pojo.SetMeal;
import com.xjx.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetMealServiceImpl implements SetmealService{

    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Autowired
    private SetMealDao setMealDao;

    @Value("${out_put_path}")//从属性文件读取输出目录的路径
    private String outputpath ;

    //新增套餐名字，同时需要关联检查组
    public void add(SetMeal setMeal, Integer[] checkgroupIds) {
        setMealDao.add(setMeal);
        Integer setMealId = setMeal.getId();
        setSetMealAndCheckGroup(setMealId,checkgroupIds);
        //将图片名称保存到redis
        String fileName = setMeal.getImg();
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,fileName);

        // 当添加套餐后需要重新生成静态页面(套餐列表页面，套餐详情页面 )
        generateMobileStaticHtml();
    }

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage,pageSize);
        Page<SetMeal> page = setMealDao.findByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public List<SetMeal> findAll() {
        return setMealDao.findAll();
    }

    @Override
    public SetMeal findById(int id) {
        return setMealDao.findById(id);

    }

    //设置套餐和检查组多对多的关系，操作t_setmeal_checkgroup
    public void setSetMealAndCheckGroup(Integer setMealId,Integer[] checkgroupIds){
        if (checkgroupIds!=null&&checkgroupIds.length>0){
            for (Integer checkgroupId : checkgroupIds) {
                Map<String,Integer> map = new HashMap();
                map.put("setmealId",setMealId);
                map.put("checkgroupId",checkgroupId);
                setMealDao.setSetMealAndCheckGroup(map);
            }
        }
    }

    // 用于生成静态页面
    public void generateHtml(String templateName, String htmlPageName, Map map){
        Configuration configuration = freeMarkerConfigurer.getConfiguration();// 获取配置对象
        Writer out = null;
        try {
            Template template = configuration.getTemplate(templateName);
            // 构造输出流
            out = new FileWriter(new File(outputpath + "/" + htmlPageName));
            // 输出文件
            template.process(map,out);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if (null != out) {
                    out.flush();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    //生成当前方法所需的静态页面
    public void generateMobileStaticHtml() {
        // 在生成静态页面之前需要查询数据
        List<SetMeal> list = setMealDao.findAll();

        // 需要生成套餐列表静态页面
        generateMobileSetmealListHtml(list);

        // 需要生成套餐详情静态页面
        generateMobileSetmealDetailHtml(list);

    }

    //生成套餐列表静态页面
    public void generateMobileSetmealListHtml(List<SetMeal> list) {
        Map map = new HashMap<>();
        // 为模板提供数据,用于生成静态页面
        map.put("setmealList", list);
        this.generateHtml("mobile_setmeal.ftl","m_setmeal.html",map);
    }

    //生成套餐详情静态页面（多个）
    public void generateMobileSetmealDetailHtml(List<SetMeal> list) {
        for (SetMeal setmeal : list) {
            Map map = new HashMap();
            map.put("setmeal", setMealDao.findById(setmeal.getId()));
            this.generateHtml("mobile_setmeal_detail.ftl",
                    "setmeal_detail_"+setmeal.getId()+".html",
                    map);
        }
    }

}
